package org.xyz.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class PhoneUtil {
    private static String sWxAppid;
    private static String sWxAppsecret;

    @Value("${wx.app_id}")
    private String wxAppid;

    @Value("${wx.app_secret}")
    private String wxAppsecret;

    @PostConstruct
    public void init() {
        sWxAppid = wxAppid;
        sWxAppsecret = wxAppsecret;
    }

    // Static getters
    public static String getWxAppid() {
        return sWxAppid;
    }

    public static String getWxAppsecret() {
        return sWxAppsecret;
    }

    public static JSONObject getPhoneNumber(String code) {
        JSONObject phone;
        String appid = getWxAppid();
        String appSec = getWxAppsecret();
        // 获取token
        String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
               appid , appSec);
        try {
            JSONObject token = JSON.parseObject(HttpUtil.get(token_url));
            if (token == null) {
                log.info("获取token失败");
                return null;
            }
            String accessToken = token.getString("access_token");
            if (StringUtils.isEmpty(accessToken)) {
                log.info("获取token失败");
                return null;
            }
            log.info("token : {}", accessToken);
            //获取phone
            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
                    + "?access_token=" + accessToken;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", code);

            String reqJsonStr = JSONUtil.toJsonStr(jsonObject);
            phone = JSON.parseObject(HttpUtil.post(url, reqJsonStr));

            if (phone == null) {
                log.info("获取手机号失败");
                return null;
            }
            return phone;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
